import React, {Component} from 'react'
import moment from 'moment'
import { Input, DatePicker, Button, Select, Form, Radio, message } from 'antd'
import { myFetch, config } from '../utils'

const Search =　Input.Search
const Option = Select.Option
const FormItem = Form.Item
const RadioGroup = Radio.Group

class StudentDetail extends Component {
  constructor() {
    super()
    this.state = {
      value: 1,
    }
    this.onRadioChange = this.onRadioChange.bind(this)
    this.directorChange = this.directorChange.bind(this)
    this.needChange = this.needChange.bind(this)
    this.modifyCusomer = this.modifyCusomer.bind(this)
    this.delCustomer = this.delCustomer.bind(this)
  }

  onRadioChange(e) {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value,
    })
  }

  directorChange(value) {
    console.log(`selected ${value}`);
  }

  needChange(value) {
    console.log(`selected ${value}`);
  }
  render() {
    const { data, common: { types, sources, levels, managers } } = this.props
    const { getFieldDecorator, resetFields } = this.props.form
    const { manager, demand } = data
    let initManager = []
    if (manager && manager.length > 0) {
      initManager = manager.map(v => {
        if (v._id) return v._id
        if (v) return v
      })
    }
    let initDemand = []
    if (demand) {
      const str = demand.replace(/,$/, '')
      initDemand = str.split(',')
    }
    const children = []
    for (let i = 10; i < 36; i++) {
      children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>)
    }
    return (
      <div>
        <div className="rt-stu-new">
          <Form inline className="rt-form-new">
            <FormItem
              label="姓名"
            >
              {getFieldDecorator('name', {
                initialValue: data.name,
              })(
                <Input placeholder="请输入学员姓名" />
              )}
            </FormItem>
            <FormItem className="rt-radio-stu">
              {getFieldDecorator('genre', {
                initialValue: data.genre ? data.genre._id : null,
              })(
                <RadioGroup>
                  {
                    types.map(v => (
                      <Radio key={v._id} value={v._id}>{v.name}</Radio>
                    ))
                  }
                </RadioGroup>
              )}
            </FormItem>
            <FormItem
              label="电话"
            >
            {getFieldDecorator('mobile', {
              initialValue: data.phoneNumber,
            })(
              <Input placeholder="请输入学员电话"/>
            )}
            </FormItem>
            <FormItem
              label="邮箱"
            >
            {getFieldDecorator('email', {
              initialValue: data.email,
            })(
              <Input placeholder="请输入学员邮箱"/>
            )}
            </FormItem>
            <FormItem
              label="公司"
            >
            {getFieldDecorator('company', {
              initialValue: data.company,
            })(
              <Input />
            )}
            </FormItem>
            <FormItem
              label="职位"
            >
            {getFieldDecorator('position', {
              initialValue: data.position,
            })(
              <Input />
            )}
            </FormItem>
            <FormItem
              className="rt-source-select"
              label="来源"
            >
              {getFieldDecorator('source', {
                initialValue: data.source ? data.source._id : null,
              })(
                <Select placeholder="网络渠道">
                  {
                    sources.map(v => (
                      <Option key={v._id} value={v._id}>{v.name}</Option>
                    ))
                  }
                </Select>
              )}
            </FormItem>
            <FormItem
              label="创建日期"
            >
              {getFieldDecorator('newDate', {
                initialValue: moment(data.createdAt),
              })(
                <DatePicker placeholder="请选择日期" />
              )}
            </FormItem>
          </Form>
          <Form className="rt-form-level" inline>
            <FormItem
              className="rt-stu-need"
              label="需求"
            >
            {getFieldDecorator('need', {
              initialValue: initDemand,
            })(
              <Select
                tags
                style={{ width: '100%' }}
                className="rt-select-tag"
                onChange={this.needChange}
                tokenSeparators={[',']}
              >
                {children}
              </Select>
            )}
            </FormItem>
            <FormItem
              label="级别"
              className="rt-stu-lev"
            >
            {getFieldDecorator('level', {
              initialValue: data.level ? data.level._id : null,
            })(
              <Select placeholder="客户类型">
                {
                  levels.map(v => (
                    <Option key={v._id} value={v._id}>{v.name}</Option>
                  ))
                }
              </Select>
            )}
            </FormItem>
          </Form>
          <Form inline className="rt-form-new">
            <FormItem
              label="负责人"
            >
              {getFieldDecorator('manager', {
                initialValue: initManager,
                // initialValue: manager.map(v => v._id).length > 0 ? manager.map(v => v._id) : [],
              })(
                <Select
                  tags
                  style={{ width: '100%' }}
                  className="rt-select-tag"
                  onChange={this.directorChange}
                  tokenSeparators={[',']}
                >
                  {
                    managers.map(v => (
                      <Option key={v._id} value={v._id}>{v.username}</Option>
                    ))
                  }
                </Select>
              )}
            </FormItem>
            <FormItem
              label="下次沟通"
            >
              {getFieldDecorator('nextDate', {
                initialValue: moment(data.nextAt),
              })(
                <DatePicker placeholder="请选择日期" />
              )}
            </FormItem>
          </Form>
        </div>

        <div className="cl rt-modal-foot">
          <Button
            className="lf rt-btn-update"
            onClick={this.modifyCusomer}
          >
            修改
          </Button>
          <Button
            className="rf rt-btn-del"
            onClick={this.delCustomer}
          >
            删除
          </Button>
        </div>
      </div>
    )
  }
  componentWillReceiveProps(nextProps) {
    const { form: { resetFields } } = this.props
    if (nextProps.modal === false) {
      resetFields()
    }
  }
  modifyCusomer() {
    const { form: { validateFields }, data, closeModal, common: { managers } } = this.props
    validateFields((err, fieldsValue) => {
      if (err) {
        return
      }
      const values = {
        ...fieldsValue,
        phoneNumber: fieldsValue['mobile'],
        createdAt: fieldsValue['newDate'].format(config.dateFormat),
        nextAt: fieldsValue['nextDate'].format(config.dateFormat),
        demand: fieldsValue['need'] ? fieldsValue['need'].join(',') : '',
      }
      if (values.manager && values.manager.length > 0) {
        const filteredArr = managers.filter(v => values.manager.includes(v._id))
        if (filteredArr.length > 0) {
          values.manager = filteredArr
        }
      }
      myFetch(`/v1/customers/${data._id}`, {method: 'PUT', body: JSON.stringify(values)})
        .then(rs => {
          if (rs && rs.ok === 1) {
            message.success('修改信息成功')
            closeModal(Object.assign({}, values, {index: data.index, nModified: rs.nModified, _id: data._id}))
          }
        })
    })
  }
  delCustomer() {
    const { data, delCallback } = this.props
    if ('undefined' === data.index || !data._id) return
    delCallback(data.index, data._id)
  }
}

export default Form.create()(StudentDetail)